# include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;

int n, ch[MAXN][2], key[MAXN], cnt, root, fa[MAXN], ans;

inline void cg(int x, int y, int d) {
    if(x) fa[x] = y;
    if(y) ch[y][d] = x;
}

inline bool lc(int o) {
    return o == ch[fa[o]][1];
}

inline void rot(int o) {
    int x = fa[o], d = lc(o);
    cg(o, fa[x], lc(x));
    cg(ch[o][!d], x, d);
    cg(x, o, !d);
    if(x == root) root = o;
}

inline int newnode(int v) {
    key[++cnt] = v;
    return cnt;
}

inline void splay(int o) {
    for(int x; (x = fa[o]); rot(o)) {
        if(fa[x]) rot(lc(o) == lc(x) ? x : o);
    }
}

inline void ins(int o, int v) {
    for(int x; (x = ch[o][v >= key[o]]); o = x);
    cg(newnode(v), o, v >= key[o]);
    splay(cnt);
}

inline int sp(int o, int t) {
    for(o = ch[o][t], t = !t; ch[o][t]; o = ch[o][t]);
    return o;
}

int main() { 
# ifndef LOCAL
    freopen("turnover.in", "r", stdin);
    freopen("turnover.out", "w", stdout);
# endif
    scanf("%d", &n);
    while(n--) {
        int x;
        if(scanf("%d", &x) == EOF) x = 0;
        if(root) ins(root, x);
        else root = newnode(x);
        int a = sp(root, 0), b = sp(root, 1), d = 0x7fffffff;
        if(a) d = min(abs(key[a] - x), d);
        if(b) d = min(abs(key[b] - x), d);
        if(!a && !b) d = x;
        ans += d;
    }
    printf("%d\n", ans);
}
